package com.ff.xyh.serurity.handler;

import com.ff.xyh.common.utils.ResponseUtil;
import com.ff.xyh.common.entity.result.ResultObject;
import com.ff.xyh.serurity.security.TokenManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>
 * 登出业务逻辑类
 * </p>
 *
 * @author qy
 * @since 2019-11-08
 */
public class TokenLogoutHandler implements LogoutHandler {

    private TokenManager tokenManager;
    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager, RedisTemplate redisTemplate) {
        this.tokenManager = tokenManager;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 实际上应该是获取token过期时间，将用户id 和 token存入redis，过期时间跟token相同，
     * 当用户访问时，如果redis存在该用户token 则对比redis里的token，否则直接放行了
     */
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        String token = request.getHeader("token");
//        System.out.println("token ==> ");
//        System.out.println(token);
        if (token != null) {
            //清空当前用户缓存中的权限数据
            String userId = tokenManager.getUserIdFromToken(token);
            tokenManager.removeToken(token, userId);
            /** 删除redis中用户token 在TokenManager.removeToken 方法中进行了 */
//            redisTemplate.delete("AccessUserService::" + userId);
            redisTemplate.delete("AccessPermissionService::" + userId); // 删除redis中用户权限列表
        }
        ResponseUtil.out(response, ResultObject.ok());
    }



}